3289. The Two Sneaky Numbers of Digitville
- 題目描述
- 解答
Description
In the town of Digitville, there was a list of numbers called nums containing integers from 0 to n - 1. Each number was supposed to appear exactly once in the list, however, two mischievous numbers sneaked in an additional time, making the list longer than usual.
As the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville.
Example 1:
Input: nums = [0,1,1,0]
Output: [0,1]
Explanation:
The numbers 0 and 1 each appear twice in the array.
Example 2:
Input: nums = [0,3,2,1,3,2]
Output: [2,3]
Explanation:
The numbers 2 and 3 each appear twice in the array.
Example 3:
Input: nums = [7,1,5,4,3,4,6,0,9,5,8,2]
Output: [4,5]
Explanation:
The numbers 4 and 5 each appear twice in the array.
Constraints:
2 <= n <= 100nums.length == n + 20 <= nums[i] < n- The input is generated such that
numscontains exactly two repeated elements.
Solution
/**
* @param {number[]} nums
* @return {number[]}
*/
var getSneakyNumbers = function (nums) {
const counter = {};
const result = [];
for (let i = 0; i < nums.length; i++) {
if (counter[nums[i]]) {
counter[nums[i]]++;
} else {
counter[nums[i]] = 1;
}
}
for (let key in counter) {
if (counter[key] === 2) {
result.push(parseInt(key));
}
}
return result;
};
解題思路
想法是使用 counter 來記錄數字出現的數量
for (let i = 0; i < nums.length; i++) {
if (counter[nums[i]]) {
counter[nums[i]]++;
} else {
counter[nums[i]] = 1;
}
}
遍歷一遍陣列後再次遍歷 counter,若出現兩次則記錄起來,最後回傳答案。
for (let key in counter) {
if (counter[key] === 2) {
result.push(parseInt(key));
}
}
心得
我的答案好像滿冗長的,不知是否可以簡化。